<?php
//include $_SERVER['DOCUMENT_ROOT'].'/application/config/Database.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/application/library/Betting_lib.php';
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

if($_POST['product_id']){
	$bet = new Betting_lib();
	$var = $bet->insert_bid($_POST['product_id']);
	notifyofbid($var);
} else {
	loadbids();
}
function loadbids(){
	$con 		= new Database();
	$result 	= $con->get_bid_status();
	//$history 	= $con->get(array('table'=>'bid_history','fields'=>array('user_id','product_id','timestamp'),'order'=>'bid_id desc'));
	$string =	"retry:1000\n";
	$string .= 'data:[';
	
	if($result->num_rows > 0){
	
		while($row = $result->fetch_object()){
			/* $button is the state of the "Bid now" button. If the user_id from the last bid on a product is your own user_id,
			 * then the $button is set to 0, else it will return 1 and the button is made active again for you to bet. 
			 */
			$button = ($_SESSION['userid'] == $row->user_id) ? 0 : 1;
			$string .= json_encode(array('id'=>$row->product_id,'user_id'=>$row->user_id,'username'=>$row->username,'value'=>$row->sum,'timestamp'=>date("H:i:s",$row->timestamp),'button'=>$button)).",";
		}
		
		$string = substr($string,0,-1);
	} else {
		$string .= json_encode(array('status'=>'no bids made'));
	}
	
	$string .= ']'."\n";

	// $string .= ',history:[';
	// if($history->num_rows > 0){
		// while($row = $result->fetch_object()){
			// $string .= json_encode(array('user_id'=>$row->user_id,'product_id'=>$row->product_id,'timestamp'=>date('H:i:s',$row->timestamp))).",";
		// }
	// }
	// 
	// 
	// $string .= ']'."\n";

	echo trim($string)."\n\n";
	echo PHP_EOL;
	ob_flush();
	flush();
}
function notifyofbid($var){
	//$string =	"event: message\n";
	//$string 	= 'data:{"msg":"testing"}'."\n\n";
	//$string =	"$json";
	
	echo trim($var);
	echo PHP_EOL;
	ob_flush();
	flush();
}